package com.eningqu.aipen.demo.common;

import android.content.Context;
import android.net.Uri;
import android.os.Build;
import androidx.core.content.FileProvider;
import com.eningqu.aipen.demo.BuildConfig;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class Common {
    // 字符串类型变量是null还是0个字符
    public static boolean isEmptyString(String string){
        if(string == null || string.length() <= 0)
            return true;
        else
            return false;
    }

    // 获取字节数据左侧的第n位是0还是1
    public static boolean ByteIndex(byte b, int n){
        int mask = 1 << n;
        if((b & mask) == 0)
            return false;   // 0
        else
            return true;    // 1
    }

    public static Uri getUri(Context context, File file) {
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }


    /**
     * MAC地址镜像翻转
     * @param mac
     * @return
     */
    public static String macMirror(String mac){

        StringBuilder sb = new StringBuilder();

        if(isEmptyString(mac)){
            return "";
        }

        String[] array = mac.split(":");

        if(null!=array && array.length==6){
            sb.append(array[5]).append(":");
            sb.append(array[4]).append(":");
            sb.append(array[3]).append(":");
            sb.append(array[2]).append(":");
            sb.append(array[1]).append(":");
            sb.append(array[0]);
        }
        return sb.toString();
    }

    public static String getString(InputStream inputStream) {
        InputStreamReader inputStreamReader = null;

        try {
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuffer stringBuffer = new StringBuffer("");

        String line;
        try {
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
                stringBuffer.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return stringBuffer.toString();
    }
}